<?php

class ProductController extends Zend_Controller_Action {

    public function init() {
        $ajaxContext = $this->_helper->getHelper("AjaxContext");
        $ajaxContext->addActionContext("getproductlist", "json");
        $ajaxContext->addActionContext("getproduct", "json");
        $ajaxContext->addActionContext("getproducttype", "json");
        $ajaxContext->addActionContext("save", "json");
        $ajaxContext->addActionContext("fileupload", "html");
        $ajaxContext->addActionContext("deleteproduct", "json");
        $ajaxContext->addActionContext("saveproductsupply", "json");
        $ajaxContext->addActionContext("deleteproductsupply", "json");
        $ajaxContext->addActionContext('export', "html");
        $ajaxContext->initContext();
    }

    public function getproductlistAction() {
        $product = new Application_Model_DbTable_Product();
        $this->_helper->getHelper('Json')->sendJson(array_values($product->getList4Grid()));
    }

    public function getproductAction() {
        $p = array();
        $listArray = array('Type' => 0, 'Usage' => 0, 'Style' => 0, 'PriceLevel' => 0, 'SpecialItem' => 0);
        $pid = $this->getRequest()->getParam("pid");
        $product = new Application_Model_DbTable_Product();
        $par = $product->find($pid)->toArray();
        foreach ($par as $kv) {
            foreach ($kv as $key => $value) {
                if (array_key_exists($key, $listArray)) {
                    $p[$key . '[]'] = explode(';', $value);
                } else {
                    $p[$key] = $value;
                }
            }
        }
        
        $sql = "select SupplyID,SupplyTypeID from ProductSupply where ProductID = ? ";        
        $sp = $product->getAdapter()->fetchAssoc($sql, array($pid));
        $p['supplies'] = array_values($sp);
        $this->_helper->getHelper('Json')->sendJson($p);
    }

    public function getproducttypeAction() {
        $typeProduct = new Application_Model_DbTable_TypeProduct();
        $this->_helper->getHelper('Json')->sendJson($typeProduct->fetchAll()->toArray());
    }

    public function saveAction() {
        $pid = $this->getRequest()->getParam("ID");
        $data = array(
            'Name' => $this->getRequest()->getParam("Name", ""),
            'Ref' => $this->getRequest()->getParam("Ref", ""),
            'Type' => implode(';', $this->getRequest()->getParam("Type", array())),
            'Usage' => implode(';', $this->getRequest()->getParam("Usage", array())),
            'Style' => implode(';', $this->getRequest()->getParam("Style", array())),
            'Price' => $this->getRequest()->getParam("Price", 0),
            'PriceLevel' => implode(';', $this->getRequest()->getParam("PriceLevel", array())),
            'SetWeight' => $this->getRequest()->getParam("SetWeight", 0),
            'UnitWeight' => $this->getRequest()->getParam("UnitWeight", 0),
            'SpecialItem' => implode(';', $this->getRequest()->getParam("SpecialItem", array())),
            'DisplayFeather' => $this->getRequest()->getParam("DisplayFeather", ""),
            'BestSeller' => $this->getRequest()->getParam("BestSeller", ""),
            'DisplaySex' => $this->getRequest()->getParam("DisplaySex", ""),
            'SpecialOffer' => $this->getRequest()->getParam("SpecialOffer", ""),
            'SpecialOfferText' => $this->getRequest()->getParam("SpecialOfferText", ""),
            'Size' => $this->getRequest()->getParam("Size", ""),
            'MainFabrics' => $this->getRequest()->getParam("MainFabrics", ""),
            'PackingDetail' => $this->getRequest()->getParam("PackingDetail", ""),
            'MOQ' => $this->getRequest()->getParam("MOQ", ""),
            'ProductDescription' => $this->getRequest()->getParam("ProductDescription", ""),
            'Like' => $this->getRequest()->getParam("Like", ""),
            'ProductTypeID' => $this->getRequest()->getParam("ProductTypeID", 0),
            'InnerOrg' => $this->getRequest()->getParam("InnerOrg", 0),
            'OuterOrg' => $this->getRequest()->getParam("OuterOrg", 0),
            'Expandable' => $this->getRequest()->getParam("Expandable", 0),
            'UpdateTime' => date('Y-m-d H:i:s')
        );

        $product = new Application_Model_DbTable_Product();
        if (empty($pid)) {
            $data['CreateTime'] = date('Y-m-d H:i:s');
            $product->insert($data);
            $pid = $product->getAdapter()->lastInsertId();
        } else {
            $where = $product->getAdapter()->quoteInto("ID = ?", intval($pid));
            $product->update($data, $where);
        }
        $this->_helper->getHelper('Json')->sendJson(array('id' => $pid, 'message' => 'Save Successfully'));
    }

    public function fileuploadAction() {
        $id = $this->getRequest()->getParam("pid");
        $allowedExts = array("jpg", "jpeg", "gif", "png");
        $name = $_FILES["file"]["name"];
        $extension = substr($name, strrpos($name, '.') + 1);
        $filename = 'product' . uniqid($id) . '.' . $extension;
        $product = new Application_Model_DbTable_Product();
        if ((($_FILES["file"]["type"] == "image/gif")
                || ($_FILES["file"]["type"] == "image/jpeg")
                || ($_FILES["file"]["type"] == "image/pjpeg")
                || ($_FILES["file"]["type"] == "image/png"))
                && in_array($extension, $allowedExts)) {
            $result = $product->find($id);
            $sp = $result->toArray();
            $photo = $sp[0]['Photo'];
            if (file_exists(UPLOAD_PATH . DIRECTORY_SEPARATOR . $photo)) {
                @unlink(UPLOAD_PATH . DIRECTORY_SEPARATOR . $photo);
            }
            move_uploaded_file($_FILES["file"]["tmp_name"], UPLOAD_PATH . DIRECTORY_SEPARATOR . $filename);
        }

        $data = array("photo" => $filename);
        $where = $product->getAdapter()->quoteInto(' ID = ?', $id);
        $product->update($data, $where);
        Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer')->setNoRender(true);
        Zend_Layout::getMvcInstance()->disableLayout();
        $response = '<textarea>' . $filename . '</textarea>';
        $this->getResponse()->setBody($response);
    }

    public function deleteproductAction() {
        $pid = $this->getRequest()->getParam("pid");
        if (!empty($pid)) {
            $product = new Application_Model_DbTable_Product();
            $result = $product->find($pid);
            $sp = $result->toArray();
            $photo = $sp[0]['Photo'];
            if (file_exists(UPLOAD_PATH . DIRECTORY_SEPARATOR . $photo)) {
                @unlink(UPLOAD_PATH . DIRECTORY_SEPARATOR . $photo);
            }
            $where = $product->getAdapter()->quoteInto("ID = ?", intval($pid));
            $product->delete($where);
            $condition = $product->getAdapter()->quoteInto("ProductID = ? ", intval($pid));
            $productSupply = new Application_Model_DbTable_ProductSupply();
            $productSupply->delete($condition);
        }
        $this->_helper->getHelper('Json')->sendJson(array('id' => $pid, 'message' => 'Delete Successfully'));
    }

    public function saveproductsupplyAction() {
        $productid = $this->getRequest()->getParam("productId");
        $supplyId = $this->getRequest()->getParam("supplyId");
        $supplytypeId = $this->getRequest()->getParam("supplytypeId");
        $productsupply = new Application_Model_DbTable_ProductSupply();
        $where = "ProductID = " . $productid . " and SupplyID = " . $supplyId;
        $productsupply->getAdapter()->delete("ProductSupply", $where);
        $data = array(
            'ProductID' => $productid,
            'SupplyID' => $supplyId,
            'SupplyTypeID' => $supplytypeId
        );        
        $productsupply->getAdapter()->insert("ProductSupply", $data);

        $this->_helper->getHelper('Json')->sendJson(array('message' => 'Add Successfully'));
    }

    public function deleteproductsupplyAction() {
        $productid = $this->getRequest()->getParam("productId");
        $supplyTypeId = $this->getRequest()->getParam("supplyTypeId");
        $productsupply = new Application_Model_DbTable_ProductSupply();
        $where = "ProductID = " . $productid . " and SupplyTypeID = " . $supplyTypeId;
        $productsupply->getAdapter()->delete("ProductSupply", $where);

        $this->_helper->getHelper('Json')->sendJson(array('message' => 'Delete Successfully'));
    }
    
    
     public function exportAction() {
        $filename = 'products.csv';
        Zend_Layout::getMvcInstance()->disableLayout();
        Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer')->setNoRender(true);
        $this->getResponse()->setHttpResponseCode(200);
        $this->getResponse()->setHeader('Content-Type', 'application/csv', true);
        $this->getResponse()->setHeader('Content-Disposition', 'inline; filename="' . $filename . '"', true);
        $this->getResponse()->setHeader('Cache-Control', 'public', true);
        $this->getResponse()->setHeader('Pragma', 'public', true);
        $content = "";
        $product = new Application_Model_DbTable_Product();
        $records = $product->fetchAll()->toArray();
        $heads = array_keys($records[0]);
        $content = $content . implode(',', $heads) . "\n";
        foreach ($records as $record) {
            $content = $content . implode(',', array_values($record))."\n";
        }
        $this->getResponse()->setBody($content);
    }

}
